//
//  TJTemplateEditController.m
//  BaoDian
//
//  Created by mac on 2024/8/15.
//

#import "TJTemplateEditController.h"
#import "TJStyle1Button.h"

#import "TJVideoCoverDownloader.h"
#import "TJButton.h"
#import "TJSelectColorController.h"
#import "ZFSliderView.h"
#import "ZFPlayerController.h"

#import "UIView+ZFFrame.h"
#import "ZFUtilities.h"
#import "ZFPlayerConst.h"
#import "TJEditTextController.h"
#import "TJUIAlertController.h"
#import "TJVideoPreviewController.h"
#import "TJVideoPlayController.h"
#import "TJFontStyle.h"
#import "TJSectionView.h"
 
@interface TJTemplateEditController ()<TJSectionViewDelegate>

@property (nonatomic, weak) UIImageView *coverImageView;
@property (nonatomic, weak) TJStyle1Button *uploadButton;
@property (nonatomic, weak) UILabel *tipLabel;
@property (nonatomic, weak) UIView *videoView;
@property (nonatomic, weak) UIView *uploadVideoView;
@property (nonatomic, weak) UIView *titleView;
@property (nonatomic, strong) NSMutableArray *titleSectionView;
@property (nonatomic, weak) UIView *tipView;
@property (nonatomic, weak) UIView *progressView;
@property (nonatomic, strong) ZFSliderView *slider;
@property (nonatomic, strong) UILabel *totalTimeLabel;
@property (nonatomic, strong) UILabel *currentTimeLabel;
@property (nonatomic, strong) UIButton *playOrPauseBtn;
@property (nonatomic, strong) ZFPlayerController *player;
@property (nonatomic, assign) BOOL seekToPlay;
@property (nonatomic, weak) TJButton *textButton;
@property (nonatomic, strong) NSMutableDictionary *materialJsonObj;
@property (nonatomic, strong) NSDictionary *detailData;

@property (nonatomic, strong) NSMutableArray *titleList;
@property (nonatomic, strong) UIImage *coverImage;
@property (nonatomic, strong) NSDictionary *videoDict;
@property (nonatomic, strong) NSString *videoUrl;
@property (nonatomic, strong) TJFontStyle *fontStyle;




@end

@implementation TJTemplateEditController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _seekToPlay = YES;
//    [self addUploadVideoView];
    [self addVideoView];
    [self loadData];
    [self uploadVideo];
    
}

- (void)addVideoView {
    
    UIView *view = [UIView addToView:self.view];
    view.frame = self.view.bounds;
    
    UIImageView *coverImageView = [UIImageView addToView:view];
    coverImageView.addCornerRadius(12);
    coverImageView.userInteractionEnabled = YES;
    coverImageView.contentMode = UIViewContentModeScaleAspectFit;
    CGFloat width = KScreenWidth - 36 * 2;

    _coverImageView = coverImageView;
    coverImageView.backgroundColor = UIColor.blackColor;
    
    UIView *titleView = [UIView addToView:coverImageView];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    _titleView = titleView;
    
    UIImageView *playerIconView = [UIImageView addToView:coverImageView];
    playerIconView.image = [UIImage imageNamed:@"videoPlayer_icon"];
    [playerIconView addTapGesturesWithTarget:self action:@selector(tapPlayerView)];
    [playerIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    view.hidden = YES;
    _videoView = view;
        
    UIView *bottomView = [UIView addToView:view];
    bottomView.backgroundColor = UIColorMake(0x15161A);
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(130 + TabbarSafeBottomMargin);
        make.left.right.offset(0);
        make.bottom.offset(0);
    }];
    
    [coverImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(width);
        make.centerX.offset(0);
        make.top.offset(KNavBarHight);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    TJButton *textButton = [TJButton buttonWithSuperView:bottomView font:UIFontMediumMake(12) color:UIColor.tj_8D9298Color title:@"修改文案"];
    [textButton setImage:[UIImage imageNamed:@"textFont"] forState:UIControlStateNormal];
    [textButton setImage:[UIImage imageNamed:@"textFont_select"] forState:UIControlStateSelected];
    textButton.imagePosition = QMUIButtonImagePositionTop;
    [textButton setTitleColor:UIColorMake(0x2978F0) forState:UIControlStateSelected];
    textButton.spacingBetweenImageAndTitle = 7;
    [textButton addTarget:self action:@selector(didClickTextButton:) forControlEvents:UIControlEventTouchUpInside];
    [textButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomView.mas_centerX).inset(30);
        make.width.offset(50);
        make.height.offset(56);
        make.bottom.inset(2 + TabbarSafeBottomMargin);
    }];
    
    TJButton *colorButton = [TJButton buttonWithSuperView:bottomView font:UIFontMediumMake(12) color:UIColor.tj_8D9298Color title:@"字体颜色"];
    [colorButton setImage:[UIImage imageNamed:@"textColor"] forState:UIControlStateNormal];
    [colorButton setImage:[UIImage imageNamed:@"textColor"] forState:UIControlStateSelected];
    [colorButton setTitleColor:UIColorMake(0x2978F0) forState:UIControlStateSelected];
    colorButton.imagePosition = QMUIButtonImagePositionTop;
    colorButton.spacingBetweenImageAndTitle = 7;
    [colorButton addTarget:self action:@selector(didClickColorButton) forControlEvents:UIControlEventTouchUpInside];
    [colorButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView.mas_centerX).offset(30);
        make.width.height.bottom.equalTo(textButton);
    }];
    
    UIView *progressView = [UIView addToView:bottomView];
    [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(62);
        make.left.right.offset(0);
        make.top.offset(0);
    }];
    
//    [progressView addSubview:self.playOrPauseBtn];
//    [progressView addSubview:self.currentTimeLabel];
//    [progressView addSubview:self.slider];
//    [progressView addSubview:self.totalTimeLabel];
    
    UIView *tipView = [UIView addToView:bottomView];
    [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(62);
        make.left.right.offset(0);
        make.top.offset(0);
    }];

    TJStyle1Button *previewButton = [TJStyle1Button buttonWithSuperView:tipView font:UIFontMediumMake(12) color:nil title:@"预览"];
    previewButton.addCornerRadius(15);
    previewButton.backgroundColor = UIColorMake(0x2978F0);
    [previewButton addTarget:self action:@selector(didClickPreviewButton) forControlEvents:UIControlEventTouchUpInside];
    [previewButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.inset(16);
        make.centerY.offset(0);
        make.height.offset(30);
        make.width.offset(48);
    }];
    
    UILabel *tipLabel = [UILabel lableWithSuperView:tipView font:UIFontMake(12) color:UIColor.tj_8D9298Color title:@"蓝色线框内的文案为可修改文案，蓝色线框以外的文案不可修改 点击线框修改对应文案" textAlignment:NSTextAlignmentCenter];
    tipLabel.addCornerRadius(9);
    tipLabel.numberOfLines = 0;
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(coverImageView);
        make.right.equalTo(previewButton.mas_left).inset(30);
        make.top.offset(10);
    }];
    
    _progressView = progressView;
    _tipLabel = tipLabel;
    _tipView = tipView;
    _textButton = textButton;
    
//    tipView.hidden = YES;
}

- (void)uploadVideoComplete:(void (^)(NSError *error))complete {
    
    //上传视频
    if (self.videoUrl) {
        complete(nil);
        return;
    }
    
    [TJHUD showLoadingInView:self.view];
    
    NSString *fileName = getFileNameWithPathExtension(self.videoURL.pathExtension);
    NSData *fileData = [NSData dataWithContentsOfURL:self.videoURL];
            
    [TJNetworking.shareNetwork uploadFileWithURL:@"/escrow/appTemplate/oss/upload" fileData:[NSData dataWithContentsOfURL:self.videoURL] fileKey:@"file" fileName:fileName mimeType:HJContentTypeForPathExtension(self.videoURL.pathExtension) parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
        [TJHUD hiddenLoadingInView:self.view];
        
        self.videoDict = data;
        self.videoUrl = data[@"videoUrl"];
        NSString *cacheKey = self.videoUrl.md5;

        if (self.coverImage && self.coverImage.size.width) {
            NSData *imageData = UIImageJPEGRepresentation(self.coverImage, 0.65);
            [[SDImageCache sharedImageCache] storeImageData:imageData forKey:cacheKey completion:nil];
        }
        
        complete(nil);
    } failure:^(NSError * _Nonnull error) {
        complete(error);
    }];
}


- (void)didClickPreviewButton {
    
    if (self.textButton.isSelected) {
        [self didClickTextButton:self.textButton];
    }
    
    
    [self uploadVideoComplete:^(NSError *error) {
        if (error) {
            [TJHUD showMessage:@"上次失败, 请稍后再试!"];
            return;
        }
        
        TJVideoPreviewController *videoPreviewController = [[TJVideoPreviewController alloc] init];
        videoPreviewController.model = self.model;
        videoPreviewController.titleList = self.titleList;
        videoPreviewController.materialJsonObj = self.materialJsonObj;
        videoPreviewController.videoURL = self.videoURL;
        videoPreviewController.coverImage = self.coverImage;
        videoPreviewController.videoDict = self.videoDict;
        videoPreviewController.detailData = self.detailData;
        [self.navigationController pushViewController:videoPreviewController];
    }];
}

#pragma mark - ZFSliderViewDelegate

- (void)sliderTouchBegan:(float)value {
    self.slider.isdragging = YES;
}

- (void)sliderTouchEnded:(float)value {
    if (self.player.totalTime > 0) {
        self.slider.isdragging = YES;
        @zf_weakify(self)
        [self.player seekToTime:self.player.totalTime*value completionHandler:^(BOOL finished) {
            @zf_strongify(self)
            self.slider.isdragging = NO;
            if (finished) {
            }
        }];
        if (self.seekToPlay) {
            [self.player.currentPlayerManager play];
        }
    } else {
        self.slider.isdragging = NO;
        self.slider.value = 0;
    }
}

- (void)sliderValueChanged:(float)value {
    if (self.player.totalTime == 0) {
        self.slider.value = 0;
        return;
    }
    self.slider.isdragging = YES;
    NSString *currentTimeString = [ZFUtilities convertTimeSecond:self.player.totalTime*value];
    self.currentTimeLabel.text = currentTimeString;
}

- (void)sliderTapped:(float)value {
    [self sliderTouchEnded:value];
    NSString *currentTimeString = [ZFUtilities convertTimeSecond:self.player.totalTime*value];
    self.currentTimeLabel.text = currentTimeString;
}


- (void)didClickTextButton:(TJButton *)button {
    button.selected = !button.selected;
    
    if (button.selected) {
//        _tipView.hidden = NO;
//        _progressView.hidden = YES;
    } else {
//        _tipView.hidden = YES;
//        _progressView.hidden = NO;
    }
    
    for (TJSectionView *sectionView in self.titleSectionView) {
        sectionView.isSelect = button.selected;
    }
}

- (void)didClickColorButton {
    TJSelectColorController *selectColorController = [[TJSelectColorController alloc] init];
    [selectColorController setSelecteComplete:^(UIColor * _Nonnull color) {
        
        for (int i = 0; i < self.titleSectionView.count; i++) {
            
            TJSectionView *setionView = self.titleSectionView[i];
            
            NSMutableAttributedString *attributedString = setionView.attributedText.mutableCopy;
            [attributedString removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, attributedString.length)];
            [attributedString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, attributedString.length)];
            setionView.attributedText = attributedString;
            
            NSMutableDictionary *dict = self.titleList[i];
            NSMutableDictionary *style = [dict[@"style"] mutableCopy];
            style[@"fontColor"] = color.hexString;
            dict[@"style"] = style;
            
//            NSLog(@"dict = %@", dict);
        }
   
    }];
    [self presentViewController:selectColorController animated:NO completion:nil];
}

- (void)addUploadVideoView {
    
    UIView *view = [UIView addToView:self.view];
    view.frame = self.view.bounds;
    
    TJStyle1Button *uploadButton = [TJStyle1Button buttonWithSuperView:view font:UIFontMake(14) color:nil title:@"上传视频"];
    [uploadButton addTarget:self action:@selector(didClickUploadButton) forControlEvents:UIControlEventTouchUpInside];
    uploadButton.addCornerRadius(16);
    [uploadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.centerY.offset(-15);
        make.width.offset(80);
        make.height.offset(32);
    }];
    
    UILabel *tipLabel = [UILabel lableWithSuperView:view font:UIFontMake(14) color:UIColor.tj_8D9298Color title:@"请点击上传视频再进行设置" textAlignment:NSTextAlignmentCenter];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(uploadButton.mas_bottom).offset(12);
    }];
    _uploadVideoView = view;
}

- (void)didClickUploadButton {
    
    
}

- (void)uploadVideo {
        UIImage *image = [TJTools getVideoFirstViewImageWithURL:self.videoURL];
        self.uploadVideoView.hidden = YES;
        self.videoView.hidden = NO;
        self.coverImageView.image = image;
    self.coverImage = image;
}
 
 
- (void)loadData {
 
    [TJTemplatePresent loadTemplateDetailDataWithId:self.model.Id complete:^(NSDictionary * _Nonnull data, NSError * _Nullable error) {
        if (error) {
            return;
        }
        
        self.materialJsonObj = [data[@"materialJsonObj"] mutableCopy];
        self.detailData = data;
        self.model.hasPoi = data[@"hasPoi"];
        NSArray *titleList = data[@"materialJsonObj"][@"titleList"];
      
        if (titleList.count) {
            
            self.titleSectionView = [NSMutableArray array];
            UIView *lastLabel = nil;
            
            CGFloat maxW = KScreenWidth - 36 * 2;
            
            for (NSDictionary *  _Nonnull obj in titleList) {
                
                NSDictionary *style = obj[@"style"];
                
                NSInteger fontSize = [style[@"fontSize"] intValue] * self.titleView.tj_width / 1080.0;
                NSInteger strokeWidth = [style[@"outline"] intValue] / 1.5;
                NSInteger shadowBlurRadius = [style[@"shadow"] intValue] / 1.5;
                
                
                NSAttributedString *attributedText = [self.fontStyle setTextStyleWithText:obj[@"title"] textColor:style[@"fontColor"] fontName:style[@"font"] fontSize:fontSize strokeColor:style[@"outlineColour"] strokeWidth:strokeWidth shadowColor:style[@"backColour"] shadowBlurRadius:shadowBlurRadius isItalic:[style[@"fontItalic"] boolValue] isBold:[style[@"fontBold"] boolValue] borderStyle:[style[@"borderStyle"] intValue] underline:[style[@"fontUnderline"] boolValue]];
                
                
                CGSize titleSize = [obj[@"title"] getStringSizeWithWidth:maxW font:self.fontStyle.font];
                CGRect sectionViewFrame = CGRectMake(0, 0, 0, titleSize.height);
                if (titleSize.width > maxW) {
                    sectionViewFrame = CGRectMake(0, 0, maxW, titleSize.height);
                } else {
                    sectionViewFrame = CGRectMake((maxW - (titleSize.width)) * 0.5, 0, titleSize.width, titleSize.height);
                }
                
                CGFloat bottomMargin =  [style[@"marginBottom"] intValue] / 1920.0 * self.titleView.tj_height;

                sectionViewFrame.origin.y = self.titleView.tj_height - bottomMargin - sectionViewFrame.size.height;
                      
                TJSectionView *sectionView = [[TJSectionView alloc] initWithFrame:sectionViewFrame];
                
                sectionView.text = obj[@"title"];
                sectionView.delegate = self;
                sectionView.maxW = maxW;
                
                if (isEmptyString(obj[@"indexList"])) {
                    sectionView.indexs = nil;
                } else {
                    NSArray *indexList = [obj[@"indexList"] mj_JSONObject];
                    sectionView.indexs = indexList;
                }
                
                sectionView.attributedText = attributedText;
                [self.titleView addSubview:sectionView];
                
                if ([style[@"fontItalic"] boolValue]) {
                    CGAffineTransform matrix = CGAffineTransformMake(1, 0, tanf(-5 * (CGFloat)M_PI / 180), 1, 0, 0);
                    sectionView.transform = matrix;
                }

                lastLabel = sectionView;
                [self.titleList addObject:obj.mutableCopy];
                [self.titleSectionView addObject:sectionView];
            }
        }
    }];
 
}
 
- (void)tapPlayerView {
    TJVideoPlayController *videoPlayController = [[TJVideoPlayController alloc] init];
    videoPlayController.localPath = self.videoURL.path;
    videoPlayController.coverImage = self.coverImage;
    [self presentViewController:videoPlayController animated:YES completion:nil];
}

- (TJFontStyle *)fontStyle {
    if (!_fontStyle) {
        _fontStyle = [[TJFontStyle alloc] init];
    }
    return _fontStyle;
}

- (NSMutableArray *)titleList {
    if (!_titleList) {
        _titleList = [NSMutableArray array];
    }
    return _titleList;
}
 
- (void)sectionView:(TJSectionView *)sectionView tapLabel:(TJSectionLabel *)label {
    
    if (!self.textButton.selected) {
        return;
    }
    
    NSInteger index = [self.titleSectionView indexOfObject:sectionView];
    NSMutableDictionary *dict = self.titleList[index];
    
    TJEditTextController *editTextController = [[TJEditTextController alloc] init];
    editTextController.text = label.model.text;
    [editTextController setComplete:^(NSString * _Nonnull text) {
        
        CGFloat maxW = KScreenWidth - 36 * 2;
        
        label.model.text = text;
        [sectionView reloadData];

        CGRect sectionViewFrame = sectionView.frame;
        
        NSString *currentText = [sectionView getCurrentText];
        dict[@"title"] = currentText;
                
        NSDictionary *style = dict[@"style"];
        
        NSInteger fontSize = ([style[@"fontSize"] intValue] / 1080.0 * self.titleView.tj_width);
        NSInteger strokeWidth = [style[@"outline"] intValue] / 1.5;
        NSInteger shadowBlurRadius = [style[@"shadow"] intValue] / 1.5;

        sectionView.attributedText = [self.fontStyle setTextStyleWithText:dict[@"title"] textColor:style[@"fontColor"] fontName:style[@"font"] fontSize:fontSize strokeColor:style[@"outlineColour"] strokeWidth:strokeWidth shadowColor:style[@"backColour"] shadowBlurRadius:shadowBlurRadius isItalic:[style[@"fontItalic"] boolValue] isBold:[style[@"fontBold"] boolValue] borderStyle:[style[@"borderStyle"] intValue] underline:[style[@"fontUnderline"] boolValue]];

        CGSize titleSize = [currentText getStringSizeWithWidth:maxW font:self.fontStyle.font];
        sectionViewFrame.origin.x = (maxW - (titleSize.width)) * 0.5;
        sectionViewFrame.size = CGSizeMake(maxW, titleSize.height);
        
        sectionView.frame = sectionViewFrame;
    }];
    [self presentViewController:editTextController animated:NO completion:nil];
    
}


@end
